﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.Internal.Xml.XPath;

namespace Blackbird.Studio.Mvvm
{
    public class MessageCenter : MarshalByRefObject
    {
        private static MessageCenter _instance;
        public static MessageCenter Instance { get { return _instance ?? (_instance = new MessageCenter()); } }
        public override object InitializeLifetimeService()
        {
            return null;
        }

        private readonly List<IMessageReceiver> _receivers;

        private MessageCenter()
        {
            _receivers = new List<IMessageReceiver>();
        }

        public void Register(IMessageReceiver receiver)
        {
            _receivers.Add(receiver);
        }
        
        public void Unregister(IMessageReceiver receiver)
        {
            _receivers.Remove(receiver);
        }

        public void Clear()
        {
            _receivers.Clear();
        }

        public void SendMessage<TSender>(TSender sender, string message) where TSender: ViewModelBase
        {
            _receivers.ForEach(receiver =>  SendMessageTo(sender, message, receiver));
        }

        private void SendMessageTo<TSender>(TSender sender, string message, IMessageReceiver receiver) where TSender: ViewModelBase
        {
            if(receiver != null)
            {
                receiver.ReceiveMessage(sender, message);
            }
        }
    }
}
